//
//  WithdrawVC.swift
//  d11
//
//  Created by peale on 2018/11/14.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
import Eagleeyes.DevicePrint
class WithdrawVC: BXBaseVC,UITableViewDelegate,UITableViewDataSource {
    let  reuseIdentifierID : String = "WithdrawBankCell"
    let  reuseIdentifierID2 : String = "WithdrawAddBankCell"
    let  reuseIdentifierID3 : String = "WithdrawInputMoneyCell"
    let  reuseIdentifierID4 : String = "WithdrawInputCell"
    let  reuseIdentifierID5 : String = "WithdrawHintCell"
    let  reuseIdentifierID6 : String = "WithdrawBtnCell"
    let  reuseIdentifierID7 : String = "WithdrawInputMoney2Cell"
    var balanceButton: UIButton?
    var isNewUser : Bool = true
    var popView : WithdrawPopBankListView?
    var isPopShow : Bool = false
    var type :Int = 0 //1.老注册用户未完善过信息需要提款密码  2.新注册用户(不需要取款密码) 3完善信息跳转过来的
    var dataArray : [[String:Any]]?
    var pwdStr:String?
    var moneyStr:String?
    var selectBankIndex :Int = -1
    var selectDict :[String:Any]?
    var process : String? //取款审核中的数目
    var withdraw_min : String? //取款最低金额
    var withdraw_max : String? //取款最高金额
    var  withdrawdaymax : String? //每天取款最高金额
    var withdrawdaylimit: String? //每天取款最高次数
    var playerdailywithdrawtimes :Int = 0
    var playerdailywithdrawamount :Int = 0
    var isShowPwd : Bool = false
    var userBalance : Double = 0
    lazy var tableView:UITableView = {
        let table = UITableView(frame:CGRect(x: 0, y: 0, width: self.view.width, height:kScreenHeight), style:UITableView.Style.plain)
        table.dataSource = self
        table.delegate = self
        //table.layoutMargins = UIEdgeInsets.zero
        table.separatorStyle = .none
        table.backgroundColor  = UIColor.white
        table.showsVerticalScrollIndicator = false
        table.tableFooterView = UIView.init()
        table.separatorStyle = .none
        table.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        table.estimatedRowHeight = 0
        table.estimatedSectionHeaderHeight = 0
        table.estimatedSectionFooterHeight = 0
        if #available(iOS 11.0, *) {
            table.contentInsetAdjustmentBehavior = .never
            
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        return table
    }()
    @objc override func currentViewControllerShouldPop() -> Bool {
        if self.type == 3 {
            self.navigationController?.popToRootViewController(animated: true)
        }
        return true
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let topLogo = UIImage(named: "icon_nav_left_logo")
        let titleView = UIView()
        let topLogoView = UIImageView(image: topLogo)
        titleView.addSubview(topLogoView)
        topLogoView.contentMode = .scaleToFill
        topLogoView.frame = CGRect(x: -(137/2), y:-(35/2), width: 137, height: 35)
        navigationItem.titleView = titleView
        
        self.balanceButton = self.initRightBarBtn()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: balanceButton!)
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(self.tableView)
        //获取取款限制
        self.getWithdrawLimit()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.refreshBalance()
        
    }
    
    func refreshBalance(){
        if UserHelper.getLoginStatus() {
            print("\(String(describing: GlobalInfo.memberInfoData))")
            if let withBalance = GlobalInfo.memberInfoData!["balance"] as? String {
                if withBalance != ""{
                    let balance: Double = Double(withBalance)!
                    self.userBalance = balance
                    self.balanceButton?.setTitle(String(format: "%.2f", balance), for: .normal)
                    let size = self.balanceButton!.intrinsicContentSize
                    balanceButton!.frame.size = CGSize(width: size.width, height: 33)
                }else{
                    self.balanceButton?.setTitle(String(format: "0.00"), for: .normal)
                }
            }
        }else{
            let button1 = UIBarButtonItem(title: "注册/登录", style: .plain, target: self, action: #selector(self.loginRegisterButtonClick))
            button1.tintColor = HexRGBAlpha(0xFBBC64,1)
            self.navigationItem.setRightBarButtonItems([button1], animated: false)
        }
    }
    
    @objc func loginRegisterButtonClick(){
        setRootLoginVC()
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.dataArray == nil || (self.dataArray?.count)! <= 0{
            return 1
        }
        return 4
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            if self.dataArray == nil || (self.dataArray?.count)! <= 0{
                return 1
            }
            return 2
        }else if section == 1{
            if isNewUser == true{
                 return 1
            }
            return 2
        }else if section == 2{
            return 1
        }else if section == 3{
            return 1
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0{
            if self.dataArray == nil || (self.dataArray?.count)! <= 0{
                return 66
            }else{
                if indexPath.row == 0{
                    return 82
                }else{
                    return 66
                }
            }
           
        }else if indexPath.section == 1{
            if isNewUser == false{
                if indexPath.row == 0{
                     return 101.5
                }else if indexPath.row == 1{
                     return 58
                }
            }else{
                return 101.5
            }
        }else if indexPath.section == 2{
            return 200
        }else if indexPath.section == 3{
            return 50
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView.init()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
              if self.dataArray == nil || (self.dataArray?.count)! <= 0{//添加银行卡
                var cell :WithdrawAddBankCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID2 as String) as? WithdrawAddBankCell
                if cell == nil {
                    cell =  WithdrawAddBankCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID2 as String)
                }
                 cell?.setData(isNoBank: true)
                return cell!
              }else{
                if indexPath.row == 0{ //选择银行卡
                    var cell :WithdrawBankCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID as String) as? WithdrawBankCell
                    if cell == nil {
                        cell =  WithdrawBankCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID as String)
                        cell?.showBankBtn?.addTarget(self, action: #selector(self.actionToSelectBank), for: .touchUpInside)
                    }
                    cell?.setdata(isTop: self.isPopShow,dict: self.selectDict)
                    return cell!
                }else{ //添加银行卡
                    var cell :WithdrawAddBankCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID2 as String) as? WithdrawAddBankCell
                    if cell == nil {
                        cell =  WithdrawAddBankCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID2 as String)
                    }
                   cell?.setData(isNoBank: false)
                    return cell!
                }
            }
           
        }else if indexPath.section == 1{
            if isNewUser == false{ //老用户未完善信息需要填写取款密码
                if indexPath.row == 0{ //输入金额
                    var cell :WithdrawInputMoney2Cell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID7 as String) as? WithdrawInputMoney2Cell
                    if cell == nil {
                        cell =  WithdrawInputMoney2Cell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID7 as String)
                    }
                    cell?.callChangeBlock({ (money) in
                         self.moneyStr = money
                    })
                    cell?.setData(money:self.moneyStr)
                    return cell!
                }else if indexPath.row == 1{ //取款密码
                    var cell :WithdrawInputCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID4 as String) as? WithdrawInputCell
                    if cell == nil {
                        cell =  WithdrawInputCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID4 as String)
                    }
                    cell?.callChangeBlock({ (pwd) in
                        self.pwdStr = pwd
                    })
                    cell?.showCallChangeBlock({ (isShow) in
                        self.isShowPwd = isShow
                        self.tableView.reloadData()
                    })
                    cell?.setData(inputText: self.pwdStr, row: indexPath.row,isShow:self.isShowPwd)
                    return cell!
                }
           
            }else{ //输入金额
                var cell :WithdrawInputMoneyCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID3 as String) as? WithdrawInputMoneyCell
                if cell == nil {
                    cell =  WithdrawInputMoneyCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID3 as String)
                }
                cell?.callChangeBlock({ (money) in
                    self.moneyStr = money
                })
                cell?.setData(money: self.moneyStr)
                return cell!
            }
         
          
        }else if indexPath.section == 2{ //提示
            var cell :WithdrawHintCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID5 as String) as? WithdrawHintCell
            if cell == nil {
                cell =  WithdrawHintCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID5 as String)
            }
            cell?.setData(isRed: false)
            return cell!
        }else if indexPath.section == 3{ //提交按钮
            var cell :WithdrawBtnCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID6 as String) as? WithdrawBtnCell
            if cell == nil {
                cell =  WithdrawBtnCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID6 as String)
            }
            cell?.callClickBlock({
                //提交
                self.submitData()
            })
            return cell!
        }
        return UITableViewCell.init()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if  indexPath.section == 0 {
            if self.dataArray == nil || (self.dataArray?.count)! <= 0{//添加银行卡
                if indexPath.row == 0{
                    let vc = WithdrawAddVC()
                    vc.process = self.process
                    vc.withdraw_max = self.withdraw_max
                    vc.withdraw_min = self.withdraw_min
                    vc.withdrawdaymax = self.withdrawdaymax
                    vc.withdrawdaylimit = self.withdrawdaylimit
                    vc.isNewUser = self.isNewUser
                    vc.playerdailywithdrawtimes =  self.playerdailywithdrawtimes
                    vc.playerdailywithdrawamount = self.playerdailywithdrawamount
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }else{
                 if indexPath.row == 0{
                    //选择银行卡
                    self.actionToSelectBank()
                }else if indexPath.row == 1{
                    let vc = WithdrawAddVC()
                    vc.process = self.process
                    vc.withdraw_max = self.withdraw_max
                    vc.withdraw_min = self.withdraw_min
                    vc.withdrawdaymax = self.withdrawdaymax
                    vc.withdrawdaylimit = self.withdrawdaylimit
                    vc.isNewUser = self.isNewUser
                    vc.playerdailywithdrawtimes =  self.playerdailywithdrawtimes
                    vc.playerdailywithdrawamount = self.playerdailywithdrawamount
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
           
        }
    }
    
    //选择银行卡
    @objc func actionToSelectBank() -> Void {
        if self.isPopShow{
            self.isPopShow = false
             popView?.dissmiss()
        }else{
             var popArray  = self.dataArray
            for(index,value) in (popArray?.enumerated())!{
                if value["wdbankid"] as? String ?? "-1" == self.selectDict?["wdbankid"] as? String ?? "-2"{
                    popArray?.remove(at: index)
                    break
                }
            }
            //这里判断是否只有一张卡 如果只有一张则不弹出选择
            popView = WithdrawPopBankListView.init(list: popArray, top:82)
            popView?.callClickBlock({ (row,dict) in
                if dict != nil{
                    let wdbankid = dict!["wdbankid"] as? String ?? "-2"
                    for (index,value) in (self.dataArray?.enumerated())!{
                        if wdbankid == value["wdbankid"] as? String ?? "-1"{
                            self.selectDict = value
                            self.selectBankIndex = index
                            break
                        }
                    }
                }
                 DispatchQueue.main.async {
                    self.isPopShow = false
                     self.tableView.reloadData()
                }
            })
            self.view.addSubview(popView!)
            popView?.show()
            self.isPopShow = true
        }
        self.tableView.reloadData()
      
    }
    
    //获取取款限制
    func getWithdrawLimit() -> Void {
        self.showLoadHUD(title: "")
        NetWorkRequest(API.getWithdrawLimit(url: "e5fec86"), completion: { (responseData,statusCode,strData) -> (Void) in
            DispatchQueue.main.async {
                let dataDict = responseData["data"].dictionaryObject
                self.withdrawdaymax = dataDict!["withdrawdaymax"] as? String ?? "0"
                self.withdrawdaylimit = dataDict!["withdrawdaylimit"] as? String ?? "0"
                self.playerdailywithdrawtimes = dataDict!["playerdailywithdrawtimes"] as? Int ?? 0
                self.playerdailywithdrawamount = dataDict!["playerdailywithdrawamount"] as? Int ?? 0
                self.getWithdrawBankList()
            }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                if reCode == "21002"{
                    UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                }
            }
        }) { () -> (Void) in
            DispatchQueue.main.async {
                 self.dismissLoadHUD()
                 UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
            }
        }
    }
    
    //获取银行卡列表
    func getWithdrawBankList() -> Void{
        NetWorkRequest(API.getWithdrawBankList(url: "3794aea"), completion: { (responseData,statusCode,strData) -> (Void) in
            DispatchQueue.main.async {
                 self.dismissLoadHUD()
                let dataDict = responseData["data"].dictionaryObject
                self.process = dataDict!["process"] as? String ?? "0"
                self.withdraw_min = dataDict!["withdraw_min"] as? String ?? "0"
                self.withdraw_max = dataDict!["withdraw_max"] as? String ?? "0"
                let wdpassword = dataDict!["wdpassword"] as? Bool ?? true
          //      self.isNewUser = !wdpassword
                self.dataArray = dataDict!["wd_banks"] as? [[String : Any]] ?? []
                if self.dataArray != nil && (self.dataArray?.count)!>0{
                     self.selectBankIndex = 0
                     self.selectDict = self.dataArray?[self.selectBankIndex]
//                    let totalBankList = GlobalInfo.bankList
//                    if totalBankList != nil {
//                        for  (index,dict) in (self.dataArray?.enumerated())!{
//                            for ( _,dict2) in (totalBankList?.enumerated())! {
//                                if dict["bankname"] as? String ?? "" == dict2["name"] as? String ?? ""{
//                                    var tempDict = dict
//                                    tempDict["bankicon"] =  dict2["image"] as? String ?? ""
//                                    self.dataArray![index] = tempDict
//                                    break
//                                }
//                            }
//                        }
//                    }
                }
                if self.process == "1"{
                    let vc =  WithdrawCheckingVC()
                    //                    vc.bankIconStr =  self.selectDict?["bankicon"] as? String
                    //                    vc.bankname = self.selectDict?["bankname"] as? String
                    //                    vc.cardnum =  self.selectDict?["cardnum"] as? String
                    self.navigationController?.pushViewController(vc, animated: true)
                }
                
                self.tableView.reloadData()
            }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                if reCode == "21002"{
                    UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                }
            }
        }) { () -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
            }
        }
    }
    
    //提交数据
    func submitData() -> Void {
        if playerdailywithdrawtimes >= (Int(self.withdrawdaylimit ?? "0") ?? 0){
            UIHelper.alertSimpleMessage(about: "每天取款上限为\(self.withdrawdaylimit ?? "0")次,您可以在明天继续取款！", withDescription: "", in: self)
            return
        }
//        if playerdailywithdrawamount >= (Int(self.withdrawdaymax ?? "0") ?? 0){
//            UIHelper.alertSimpleMessage(about: "每天最多可以取款金额：\(self.withdrawdaymax ?? "0")元", withDescription: "", in: self)
//            return
//        }
        if self.selectBankIndex == -1{
            UIHelper.alertSimpleMessage(about: "请添加银行卡!", withDescription: "", in: self)
            return
        }
        let money : Double = Double(self.moneyStr ?? "-1") ?? -1
        
        if self.moneyStr == nil || self.moneyStr == "0" || self.moneyStr == ""{
            UIHelper.alertSimpleMessage(about: "请输入取款金额!", withDescription: "", in: self)
            return
        }
        
        if money > self.userBalance{
            UIHelper.alertSimpleMessage(about: "余额不足", withDescription: "", in: self)
            return
        }
        if self.isNewUser == false{
            if self.pwdStr == nil || self.pwdStr == ""{
                UIHelper.alertSimpleMessage(about: "请输入取款密码!", withDescription: "", in: self)
                return
            }
            if (self.pwdStr?.count)! < 6{
                UIHelper.alertSimpleMessage(about: "取款密码错误!", withDescription: "", in: self)
                return
            }
        }
       
        let min : Double  = Double(self.withdraw_min ?? "0") ?? 0
        let max : Double  = Double(self.withdraw_max ?? "0") ?? 0
        if money < min{
            UIHelper.alertSimpleMessage(about: "取款金额不能小于\(self.withdraw_min ?? "未知错误")!", withDescription: "", in: self)
            return
        }

        if  money > max{
            UIHelper.alertSimpleMessage(about: "取款金额不能大于\(self.withdraw_max ?? "未知错误")!", withDescription: "", in: self)
            return
        }
        
        var params = [
            "addra": "",
            "addrb": "",
            "note": "",
            "address": "",
            "banknode": "",
            "bankname": "",
            "bankcode": "",
            "card": "",
            "account":"",
            "wdpassword":"",
            "amount":self.moneyStr ?? "0",
            "wdbank":self.selectDict?["wdbankid"] ?? "0",
        ]
        if self.isNewUser == false{
            params["wdpassword"]  = self.pwdStr
        }
        self.showLoadHUD(title: "提交中...")
        NetWorkRequest(API.submitWithdrawFund(url: "85077d9", params:params), completion: { (responseData,statusCode,strData) -> (Void) in
             DispatchQueue.main.async {
                 self.dismissLoadHUD()
                let dict  = responseData.dictionaryObject
                let data = dict?["data"] as? [String:Any]
                let res  = data?["response"] as? [String:Any]
                let code =  res?["c"] as? Int ?? -1
                if code == 0{
                    self.requestEagleeyes(dno:"")
                    let vc =  WithdrawCheckingVC()
                    vc.bankIconStr =  self.selectDict?["bankicon"] as? String
                    vc.bankname = self.selectDict?["bankname"] as? String
                    vc.cardnum =  self.selectDict?["cardnum"] as? String
                    self.navigationController?.pushViewController(vc, animated: true)
                }else if code == 999 || code == 1150 { //未登录
                    UIHelper.displayLoginExpireTip(self)
                } else{
                     UIHelper.alertSimpleMessage(about: "\(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                }
            }
           
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                if reCode == "21002"{
                    UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                }
            }
        }) { () -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
            }
        }
    }
    //调用鹰眼接口
    func requestEagleeyes(dno:String){
//        RequestHelper.get(atPath:"/home/getGeo", withCompletion: { (data) in
//            var dataArray = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
//            print("获取IP\(dataArray)")
//            if let ip = dataArray?["ip"] as? String {
//                DispatchQueue.main.async {
                    let blackbox :String = DevicePrint.getBlackBox() ?? ""
                    NetWorkRequest(API.requsetEagleeyes2(url: "94a0356", blackBox: blackbox, type: "withdrawal", dno: dno,ipaddress:""), completion: { (responseData,statusCode,strData) -> (Void) in
                        print("取款后鹰眼返回:",responseData,statusCode,strData)
                    }, failed: { (faildInfo,reCode,msg) -> (Void) in
                        print("取款后鹰眼返回:",faildInfo,reCode,msg)
                    }) { () -> (Void) in
                        print("取款后鹰眼返回错误")
                    }
                }
//            }
//        }, withError: { error in
//        })
//    }//withdrawal deposit
}
